<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <h3 style="margin: 20px 0;">用户管理</h3>
    <el-table stripe :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" width="150" align="center"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="150" align="center"></el-table-column>
      <el-table-column prop="avatar" label="头像" width="200" align="center">
        <template slot-scope="scope">
          <img
              style="width: 120px; height: 100px"
              :src="scope.row.avatar"/>
<!--                        :src="require('@/assets/' + scope.row.headPortrait)"/>-->

        </template>
      </el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="200" header-align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号码" width="200" align="center"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="200" align="center"></el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" width="200" align="center"></el-table-column>

      <el-table-column prop="enable" label="是否启用" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              @change="handleChangeEnable(scope.$index, scope.row.userId, scope.row.enable)"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160" align="center">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index,scope.row)">编辑
          </el-button>
          <el-dialog
              title="编辑用户"
              :visible.sync="dialogVisible"
              width="30%"
              :before-close="handleClose">
            <div style="margin: 20px;"></div>
            <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign">
              <el-form-item label="用户ID">
                <el-input v-model="formLabelAlign.id" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="formLabelAlign.username"></el-input>
              </el-form-item>
              <el-form-item label="头像">
                <el-input v-model="formLabelAlign.avatar"></el-input>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="formLabelAlign.nickname"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formLabelAlign.email"></el-input>
              </el-form-item>
              <el-form-item label="电话">
                <el-input v-model="formLabelAlign.phone"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
          </el-dialog>
          &nbsp;
          <el-button
              size="mini"
              type="danger"
              @click="openDeleteConfirm(scope.row.userId)">删除
          </el-button>

        </template>


      </el-table-column>


    </el-table>

    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20, 25]"
        :page-size="pagesize"
        :total="tableData.length"
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

  </div>
</template>

<script>
import Common from "@/views/common/Common"
export default {
  data() {
    return {
      // 每页的条数
      pagesize: 5,
      // 	currentPage 改变时会触发
      currentPage: 1,
      dialogVisible: false,
      labelPosition: 'right',
      formLabelAlign: {
        id: '',
        username: '',
        avatar: '',
        nickname: '',
        email: '',
        phone: '',
      },
      tableData: [],
      updateRoleId: 0,
    }
  },
  methods: {

    handleCommand(userId) {
      let url = 'http://localhost:8888/admin/tbUser/updateUserRole';

      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .get(url, {
            params: {
              userId: userId,
              roleId: this.updateRoleId
            }
          }).then((res) => {
        if (res.code == 2000) {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
        } else {
          this.$message(res.data.message);
        }
      }).catch((error) => {
        this.$message.error(error.data.message);
      })

    },

    handleSizeChange: function(val) {
      this.pagesize = val;
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },

    handleClose() {
      this.dialogVisible = false;
    },

    openDeleteConfirm(userId) {
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(userId);
      }).catch(() => {
      });
    },

    handleEdit(index, row) {
      this.userIndex = index;
      console.log(row.userId)
      this.formLabelAlign = {
        userId: row.userId,
        userName: row.userName,
        headPortrait: row.headPortrait,
        address: row.address,
        gender: row.gender,
        userEmail: row.userEmail,
        phone: row.phone,
      };

      this.dialogVisible = true;
    },

    confirm() {
      var that = this
      //网络请求获取数据axios
      let url = 'http://localhost:8888/admin/tbUser/updateUser';
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .post(url, this.formLabelAlign).then((response) => {
        let json = response.data;
        if (json.code == 2000) {
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          that.loadAdmins();
          this.dialogVisible = false;
        } else {
          this.$message.error(response.data.message);
        }
      })
    },

    handleDelete(userId) {
      let url = 'http://localhost:8888/admin/tbUser/' + userId + '/deleteUserById';
      this.axios
          .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let json = response.data;
        if (json.code == 2000) {
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        } else {
          this.$message.error(response.data.message);
        }
        this.loadAdmins();
      })
    },

    handleChangeEnable(i, id, toState) {
      let enableText = ['禁用', '启用'];
      // let originState = (toState + 1) % 2;
      let originState = toState;

      let url = 'http://localhost:8888/admin/tbUser/updateUserState';
      this.axios
          // .create({headers: {'Authorization': localStorage.getItem('jwt')}})
          .get(url, {
            params: {
              userId: id,
              state: originState,
            }
          }).then((res) => {
        if (res.data.code === 2000) {
          this.$message({
            message: '修改成功!',
            type: 'success'
          });
        }
      }).catch((error) => {
        this.$message.error('尝试将id=' + id + '的状态从【' + enableText[originState] + '】改为【' + enableText[toState] + '】，失败,原因为:！' + error.message);
      })
      setTimeout(() => {
        this.tableData[i].enable = originState;
      }, 200);

    },

    loadAdmins() {
      console.log('loadAdmins()');
      let url = Common.data.BASEURI+"/member/user/getList";
      this.axios
          .create({'headers': {'Authorization': "Bearer " + localStorage.getItem('jwt')}})
          .get(url).then((res) => {
        console.log(res)
        if (res.data.state == 200) {
          this.tableData = res.data.data;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },


  },
  created() {
    // created >>> 已创建，将在mounted、显示页面之前执行
    console.log('vue created');
  },
  mounted() {
    // mounted >>> 已挂载，将在created之后、显示页面之前执行
    console.log('vue mounted');
    this.loadAdmins();
  }
}
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>

